﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.BodyWeight;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.SleepWeightCommands
{
    public class SleepWeightCreateHandler : IRequestHandler<SleepWeightCreateCommand, Result>
    {
        private readonly IBaseRepository<SleepWeight> sleepweightbaseRepository;
        private readonly IMapper mapper;

        public SleepWeightCreateHandler(IBaseRepository<SleepWeight> sleepweightbaseRepository, IMapper mapper)
        {
            this.sleepweightbaseRepository = sleepweightbaseRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 羊只称重添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SleepWeightCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            SleepWeight sleepWeight = mapper.Map<SleepWeight>(request);
            //根据耳号查询数据
            var res = sleepweightbaseRepository.GetAll().Where(x => x.EarNumber == request.EarNumber&&x.WeightType==request.WeightType).FirstOrDefault();
            //获取数据不为空时，判断是哪个体重已经添加
            if (res != null)
            {
                
                    result.Code = -1;                      
            }
            else
            {

                var list = sleepweightbaseRepository.Add(sleepWeight);
                result.Code = list;

            }

            return result;
        }
    }
}
